package cn.lili.modules.statistics.serviceimpl;

import cn.lili.common.utils.CurrencyUtil;
import cn.lili.modules.order.order.client.OrderFlowStatisticsClient;
import cn.lili.modules.statistics.entity.dto.StatisticsQueryParam;
import cn.lili.modules.statistics.entity.vo.OrderOverviewVO;
import cn.lili.modules.statistics.service.PlatformViewService;
import cn.lili.modules.statistics.service.StatisticsCombineService;
import cn.lili.modules.statistics.util.StatisticsDateUtil;
import cn.lili.modules.store.entity.dto.StoreStatisticsOverviewSearchParams;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author paulG
 * @since 2022/6/28
 **/
@Service
@RequiredArgsConstructor
public class StatisticsCombineServiceImpl implements StatisticsCombineService {
    /**
     * 平台PV统计
     */
    private final PlatformViewService platformViewService;

    private final OrderFlowStatisticsClient orderFlowStatisticsClient;


    @Override
    public OrderOverviewVO overview(StatisticsQueryParam statisticsQueryParam) {
        Date[] dates = StatisticsDateUtil.getDateArray(statisticsQueryParam);


        /**
         * 组织统计初始化
         */
        StoreStatisticsOverviewSearchParams searchParams = new StoreStatisticsOverviewSearchParams();
        searchParams.setDates(dates);
        searchParams.setStatisticsQueryParam(statisticsQueryParam);
        OrderOverviewVO orderOverviewVO = orderFlowStatisticsClient.overview(searchParams);
        //访客数
        Integer uv = platformViewService.countUv(statisticsQueryParam);
        if (uv != null) {
            orderOverviewVO.setUvNum(uv.longValue());
        }

        //数据运算（转换率，比例相关）
        conversionRateOperation(orderOverviewVO);
        return orderOverviewVO;
    }

    /**
     * 运算转换率
     *
     * @param orderOverviewVO 订单统计视图
     */
    private void conversionRateOperation(OrderOverviewVO orderOverviewVO) {

        //下单转换率 订单数/UV
        Double orderConversionRate = CurrencyUtil.div(orderOverviewVO.getOrderNum(), orderOverviewVO.getUvNum(), 4);
        if (orderConversionRate > 1) {
            orderConversionRate = 1d;
        }
        orderOverviewVO.setOrderConversionRate(CurrencyUtil.mul(orderConversionRate, 100) + "%");
        //付款转换率 付款订单数/订单数
        Double paymentsConversionRate = CurrencyUtil.div(orderOverviewVO.getPaymentOrderNum(), orderOverviewVO.getOrderNum(), 4);
        if (paymentsConversionRate > 1) {
            paymentsConversionRate = 1d;
        }
        orderOverviewVO.setPaymentsConversionRate(CurrencyUtil.mul(paymentsConversionRate, 100) + "%");
        //整体转换率 付款数/UV
        Double overallConversionRate = CurrencyUtil.div(orderOverviewVO.getPaymentOrderNum(), orderOverviewVO.getUvNum(), 4);
        if (overallConversionRate > 1) {
            overallConversionRate = 1d;
        }
        orderOverviewVO.setOverallConversionRate(CurrencyUtil.mul(overallConversionRate, 100) + "%");
    }
}
